<template>
  <div>
    <el-dialog
      title="用户注册"
      center
      :visible.sync="show"
      width="40%"
      @close="closeBtn"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="头像" prop="avatar" style="width: 300px">
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :http-request="HttpRequest"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div class="del" @click="del">
              <i class="el-icon-delete" v-if="imageUrl"></i>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="昵称" prop="username">
          <el-input v-model="form.username" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" />
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input v-model="form.phone" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" />
        </el-form-item>
        <el-form-item label="图形码" prop="code">
          <div class="imgBtn">
            <el-input
              v-model="form.code"
              style="width: 300px; padding-right: 20px"
            />
            <img
              :src="codeUrl"
              alt=""
              class="imgBtn"
              @click="checkBtn"
              v-if="rcodeCheck"
            />
          </div>
        </el-form-item>
        <el-form-item label="验证码" prop="rcode">
          <el-input
            v-model="form.rcode"
            style="width: 277px; margin-right: 20px"
          />
          <el-button
            style="width: 158px"
            @click="getBtn"
            :disabled="disableds"
            >{{ msgText }}</el-button
          >
        </el-form-item>
      </el-form>
      <div class="btn">
        <el-button @click="show = false">取消</el-button>
        <el-button type="primary" @click="sureBtn">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { Register, Sendsms, uploadsPost } from '@/api/register.js'
export default {
  data () {
    return {
      codeUrl: process.env.VUE_APP_URL + '/captcha?type=sendsms',
      rcodeCheck: true,
      imageUrl: '',
      show: false,
      disableds: false,
      msgText: '获取验证码',
      // action: process.env.VUE_APP_URL + '/uploads',
      form: {
        code: '',
        username: '',
        phone: '',
        email: '',
        avatar: '',
        password: '',
        rcode: ''
      },
      rules: {
        avatar: [{ required: true, message: '请上传头像', trigger: 'change' }],
        username: [
          { required: true, message: '请输入用户名', trigger: 'change' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'change' },
          {
            pattern: /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/,
            message: '请输入正确格式',
            trigger: 'change'
          }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'change' },
          {
            pattern:
              /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/,
            message: '请输入正确格式',
            trigger: 'change'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'change' },
          {
            min: 6,
            max: 16,
            message: '密码长度在 6 到 16 个字符',
            trigger: 'change'
          }
        ],
        code: [{ required: true, message: '请输入图形码', trigger: 'change' }],
        rcode: [
          { required: true, message: '请输入验证码', trigger: 'change' },
          { min: 4, max: 4, message: '验证码长度必须是4位', trigger: 'change' }
        ]
      }
    }
  },
  methods: {
    async HttpRequest (file) {
      const ud = new FormData()
      ud.append('image', file.file)
      const res = await uploadsPost(ud)
      // console.log(res, '11')
      if (res.code === 200) {
        this.$message.success('文件上传成功')
      } else {
        this.$message.info(res.message)
      }
      // 上传头像返回的地址，就是我们注册时接口要的数据
      this.form.avatar = res.data.file_path
      this.imageUrl = process.env.VUE_APP_URL + '/' + res.data.file_path
    },
    // 上传前
    beforeAvatarUpload (image) {
      const isLt2M = image.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isLt2M
    },
    // 切换图片 静默刷新
    checkBtn () {
      this.rcodeCheck = false
      this.$nextTick(() => {
        this.rcodeCheck = true
      })
    },

    // 获取短信验证码
    async getBtn () {
      this.$refs.form.validateField(['phone', 'code'])
      const res = await Sendsms({
        phone: this.form.phone,
        code: this.form.code
      })
      console.log(res, '1')
      const { phone, code } = this.form
      if (res.code === 200 && phone !== '') {
        this.$message.success(res.data.captcha)
      } else if (res.code === 0 && phone !== '' && code !== '') {
        this.$message.error(res.message)
        this.checkBtn()
      } else {
        if (phone && code) {
          let times = 5
          const setInter = setInterval(() => {
            times--
            if (times <= 0) {
              this.msgText = '获取验证码'
              this.disableds = false
              clearInterval(setInter)
            } else {
              this.msgText = `${times}秒后重新获取`
              this.disableds = true
            }
          }, 1000)
        } else {
          return ''
        }
      }
    },
    // 确定按钮
    sureBtn () {
      this.$refs.form.validate(async (result) => {
        if (result) {
          const res = await Register(this.form)
          console.log(res)
          if (res.code === 200) {
            this.$message.success('注册成功')
            this.show = false
          } else {
            this.$message.error(res.message)
          }
        }
      })
    },
    // 关闭按钮
    closeBtn () {
      this.$refs.form.resetFields()
      this.imageUrl = ''
      this.form = {
        code: '',
        username: '',
        phone: '',
        email: '',
        avatar: '',
        password: '',
        rcode: ''
      }
    },
    // 删除图片
    del () {
      this.imageUrl = ''
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  //margin-left: 120px;
  .del {
    position: absolute;
    right: 6px;
    top: 6px;
    color: red;
    cursor: pointer;
    display: none;
  }
  &:hover {
    .del {
      display: inline-block;
    }
  }
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.btn {
  text-align: center;
  margin-top: 70px;
}
.imgBtn {
  display: flex;
  align-items: center;
  cursor: pointer;
  height: 40px;
}
</style>
